$(function() {
    'use strict';

    /** 输入框锚点跳转 */
    var winHeight = $(window).height();
    var _name = null;
    $(window).resize(function() {
        var thisHeight = $(this).height();
        if(winHeight - thisHeight > 50){
            window.location = '#'+_name;
        } else {
            _name = null;
        }
    });
    $(document).on('focus', 'input, textarea', function () {
        _name = $(this).attr('name');
    });

    /** 更新验证码 */
    $(document).on('click', '#captcha_code', function () {
        captcha_code();
    });

    /** 发送验证码 */
    $(document).on('click', '.send_verify_code', function () {
        var _this = $(this);
        if (_this.hasClass('disabled')) {
            return;
        }
        var _url = _this.data('url');
        var _type = _this.data('type');
        var _time = _this.data('time') ? _this.data('time'):120;
        var _codeid = _this.data('codeid');
        var _code = $('#' + _codeid);
        var formhash = $('input[name=formhash]').val();
        var oldverify = _this.data('oldverify');
        var _data = {};
        if (_type == 1 && !oldverify) {
            var _phoneid = _this.data('phoneid');
            var _phone = $('#' + _phoneid);
            if (!check_phone(_phone.val())) {
                $.toast('请输入正确的手机号');
                _phone.focus();
                return false;
            }
            _data = {phone: _phone.val()};
        } else if (_type == 2 && !oldverify) {
            var _emailid = _this.data('emailid');
            var _email = $('#' + _emailid);
            if (!check_email(_email.val())) {
                $.toast('请输入正确的邮箱');
                _email.focus();
                return false;
            }
            _data = {email: _email.val()};
        } else if(_type == 0) {
            var _account = $('#'+_this.data('accountid'));
            if( ! check_phone(_account.val()) && ! check_email(_account.val())) {
                $.toast('请输入正确的手机号/邮箱');
                _account.focus();
                return false;
            }
            var _data = {account:_account.val()};
        }
        if (!_code.val()) {
            $.toast('请输入图片验证码');
            _code.focus();
            return false;
        }
        _this.addClass('disabled').html('正在发送...').blur();

        /** 发送验证码 */
        Ajaxcall(_url, $.extend(_data, {
            verify_code: _code.val(),
            formhash: formhash,
            oldverify: oldverify
        }), function (data) {
            if (data.state == 1) {
                //var _time = 120;
                var settime = function () {
                    if (_time == 0) {
                        _this.removeClass('disabled').html('获取验证码');
                        clearTimeout(t);
                    } else {
                        _this.html(_time);
                        var t = setTimeout(settime, 1000);
                    }
                    _time = _time - 1;
                };
                settime();
            } else {
                _this.removeClass('disabled').html('获取验证码');
                captcha_code();
                _code.val('').focus();
                $.toast(data.msg);
            }

            var Callback = _this.data('callback');
            if (Callback) {
                Callback = eval(Callback);
                if (typeof(Callback) === "function")
                    Callback(data);
            }

        }, 'get', 'json');
    });

    /** 承接任务 */
    $(document).on('click', '.reward_apply', function () {
        var _this = $(this);
        Ajaxcall(_this.attr('href'), {}, function (data) {
            $.toast(data.msg);
            if (data.state==1) {
                var total_votes = parseInt($('#total_votes').html());
                var surplus_votes = $('#surplus_votes');
                var new_surplus_votes = parseInt(surplus_votes.html()) - 1;
                var progress_ratio = parseInt( ( total_votes - new_surplus_votes ) / total_votes * 100 );
                surplus_votes.html(new_surplus_votes);
                $('#progress_ratio').html(progress_ratio);
                $('#progress_ratio_line').css('width', progress_ratio+'%');
                setTimeout(function () {
                    window.location.href = location.origin+location.pathname + '?xapp-target=blank';
                    jsBridge.ready(function () {
                        jsBridge.close();
                    });
                }, 3000);
            } else {
                if (data.gourl) {
                    setTimeout(function () {
                        window.location.href=data.gourl;
                    }, 3000);
                }
            }
        }, 'get', 'json');
        return false;
    });

    /** 任务采纳处理 */
    $(document).on('click', '.apply-handle', function () {
        var _this = $(this);
        var acception = _this.data('acception');
        var apply_id = _this.data('apply_id');
        var tips = acception == 1 ? '您确定要采纳此任务？' : '您确定不要采纳此任务？';
        var _parent = _this.parent();
        $.confirm(tips, function () {

            //不采纳
            if(acception != 1) {
                var html = '<div class="row no-gutter apply-handle_modal">'
                            + '<div class="col-100">'
                                + '<input type="text" name="reason" class="modal-text-input" maxlength="100" placeholder="请输入原因">'
                                + '<div class="ts2">数据图（可选）</div>'
                            + '</div>'
                            + '<div class="col-33">'
                                + '<div class="reason-img file-item">'
                                    + '<input type="hidden" class="url" name="reason_img">'
                                    + '<div class="file-input uploaderImg"></div>'
                                    + '<p>上传图片</p>'
                                + '</div>'
                            + '</div>'
                            + '<div class="col-33">'
                                + '<div class="reason-img file-item">'
                                    + '<input type="hidden" class="url" name="reason_img2">'
                                    + '<div class="file-input uploaderImg"></div>'
                                    + '<p>上传图片</p>'
                                + '</div>'
                            + '</div>'
                            + '<div class="col-33">'
                                + '<div class="reason-img file-item">'
                                    + '<input type="hidden" class="url" name="reason_img3">'
                                    + '<div class="file-input uploaderImg"></div>'
                                    + '<p>上传图片</p>'
                                + '</div>'
                            + '</div>'
                            + '<div class="col-100">'
                                + '<div class="ts">失败24小时后返还名额</div>'
                            + '</div>'
                        + '</div>';

                $.modal({
                  title:  '请输入不采纳原因',
                  text: html,
                  buttons: [
                    {
                      text: '取消',
                    },
                    {
                      text: '确定',
                      onClick: function() {

                          var reason = $('.apply-handle_modal input[name="reason"]').val();
                          var reason_img = $('.apply-handle_modal input[name="reason_img"]').val();
                          var reason_img2 = $('.apply-handle_modal input[name="reason_img2"]').val();
                          var reason_img3 = $('.apply-handle_modal input[name="reason_img3"]').val();

                          if(!reason)
                          {
                              $.toast('请输入不采纳原因');
                              return;
                          }

                          var imgs = [];
                          if(reason_img)
                            imgs.push(reason_img);
                          if(reason_img2)
                            imgs.push(reason_img2);
                          if(reason_img3)
                            imgs.push(reason_img3);

                          Ajaxcall('/reward/apply/acception', {
                              acception:acception,
                              apply_id:apply_id,
                              reason:reason,
                              reason_img:imgs,
                          }, function (data) {
                              if(data.state == 1) {
                                  _parent.addClass('alert-danger').html('<i class="iconfont icon-chazi mr5"></i>不采纳');
                              }
                              $.toast(data.msg);
                          }, 'get', 'json');

                      }
                    },
                  ]
                });

                tzb_uploader();

            }else{
                //采纳
                Ajaxcall('/reward/apply/acception', {acception:acception,apply_id:apply_id}, function (data) {
                    if(data.state == 1) {
                        _parent.addClass('alert-success').html('<i class="iconfont icon-gou1 mr5"></i>已采纳');
                    }
                    $.toast(data.msg);
                }, 'get', 'json');

            }

        });
    });
    $('.accept-status').on('click','button',function () {
        var _this = $(this);
        var li_object = $(this).closest('li').find('.select_all');
        var _parent = _this.parent();
        var all_reward_id = new Array();
        $.each(li_object,function (i,obj) {
            if($(obj).prop("checked")){
                all_reward_id.push($(obj).val());
            }
        });


        if(all_reward_id.length == 0){
            $.toast('请选择要操作的内容！');
            return;
        }
        var list= all_reward_id;


        var accept_flag = _this.attr('class').indexOf('accept') >1;
        var tips =  accept_flag? '您确定要采纳所有任务？' : '您确定不采纳所有任务？';

        $.confirm(tips, function () {
            if(accept_flag){
                //采纳
                Ajaxcall('/reward/apply/acception_all', {acception:1,apply_id_str:list}, function (data) {
                    $.alert(data.msg);
                    if(data.state == 1) {
                        window.location=location;
                        _parent.addClass('alert-success').html('<i class="iconfont icon-gou1 mr5"></i>已采纳');
                    }

                }, 'get', 'json');
            }else{//不采纳
                var html = '<div class="row no-gutter apply-handle_modal">'
                    + '<div class="col-100">'
                    + '<input type="text" name="reason" class="modal-text-input" maxlength="100" placeholder="请输入原因">'
                    + '<div class="ts2">数据图（可选）</div>'
                    + '</div>'
                    + '<div class="col-33">'
                    + '<div class="reason-img file-item">'
                    + '<input type="hidden" class="url" name="reason_img">'
                    + '<div class="file-input uploaderImg"></div>'
                    + '<p>上传图片</p>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-33">'
                    + '<div class="reason-img file-item">'
                    + '<input type="hidden" class="url" name="reason_img2">'
                    + '<div class="file-input uploaderImg"></div>'
                    + '<p>上传图片</p>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-33">'
                    + '<div class="reason-img file-item">'
                    + '<input type="hidden" class="url" name="reason_img3">'
                    + '<div class="file-input uploaderImg"></div>'
                    + '<p>上传图片</p>'
                    + '</div>'
                    + '</div>'
                    + '<div class="col-100">'
                    + '<div class="ts">失败24小时后返还名额</div>'
                    + '</div>'
                    + '</div>';

                $.modal({
                    title:  '请输入不采纳原因',
                    text: html,
                    buttons: [
                        { text: '取消'},
                        {
                            text: '确定',
                            onClick: function() {
                                var reason = $('.apply-handle_modal input[name="reason"]').val();
                                var reason_img = $('.apply-handle_modal input[name="reason_img"]').val();
                                var reason_img2 = $('.apply-handle_modal input[name="reason_img2"]').val();
                                var reason_img3 = $('.apply-handle_modal input[name="reason_img3"]').val();
                                if(!reason)
                                {
                                    $.toast('请输入不采纳原因');
                                    return;
                                }
                                var imgs = [];
                                if(reason_img)
                                    imgs.push(reason_img);
                                if(reason_img2)
                                    imgs.push(reason_img2);
                                if(reason_img3)
                                    imgs.push(reason_img3);

                                Ajaxcall('/reward/apply/acception_all', {
                                    acception:0,
                                    apply_id_str:list,
                                    reason:reason,
                                    reason_img:imgs
                                }, function (data) {
                                    $.alert(data.msg);
                                    if(data.state == 1) {
                                        window.location=location;
                                        _parent.addClass('alert-danger').html('<i class="iconfont icon-chazi mr5"></i>不采纳');
                                    }
                                }, 'get', 'json');

                            }
                        }
                    ]
                });
                tzb_uploader();
            }
        });
    });
    /** 不采纳图片弹窗 */
    $(document).on('click','.reason_img_open',function () {

        var reason_img = JSON.parse($(this).siblings('.reason_img_data').html());
        var index = $(this).data('index') ? $(this).data('index'):0;

        if(!reason_img)
            return;

        $.closeModal();
        var PhotoBrowserPopup = $.photoBrowser({
            photos : reason_img,
            theme: 'dark',
            type: 'popup',
            toolbar:false,
            swipeToClose:false,
        });
        PhotoBrowserPopup.open(index);

        $('.photo-browser-popup .photo-browser-close-link,.photo-browser-zoom-container').click(function(){
            $.closeModal();
        });

    });

    /** 地区选择 */
    $(document).on('change', 'select[name="province"], select[name="city"]', function () {
        var _this = $(this);
        if(_this.attr('name') == 'province') {
            $('select[name="city"], select[name="area"]').html("<option value='0'>请选择</option>");
            var son_rname = 'city';
        } else {
            $('select[name="area"]').html("<option value='0'>请选择</option>");
            var son_rname = 'area';
        }
        Ajaxcall(region_url, {region_id:_this.val()}, function (data) {
            if(data){
                var option = '';
                for(var i = 0; i < data.data.length; i++){
                    option += "<option value='" + data.data[i].region_id + "'>" + data.data[i].region_name + "</option>";
                }
                $('select[name="' + son_rname + '"]').append(option);
            }
        }, 'get', 'json');
    });

    // 加载flag
    var loading = false;

    /** 没有翻页不显示加载图片 */
    if( ! $('#pagination').html()) {
        $('.infinite-scroll-preloader').remove();
    }
    $('#pagination').hide();

    /** 获取列表 */
    var getList = function (url) {
        Ajaxcall(url, {}, function (data) {
            if(data.state==1) {
                $('#pagination').html(data.page);
                $('.infinite-scroll-bottom .list-container').append(data.html);
            } else {
                $.toast(data.msg);
            }
        }, 'get', 'json');
    };

    /** 退出登录 */
    $(document).on('click', '.logout', function () {
        var _this = $(this);
        $.confirm('您确定要退出登录吗？', function () {
            location.href = _this.attr('href');
        });
        return false;
    });

    /** 获取下页链接 */
    var getNextPage = function () {
        var url = $('#pagination').find('a[rel="next"]').attr('href');
        return url;
    };

    /** 点击加载更多 */
    $(document).on('click', 'a.more', function () {
        var _this = $(this);
        Ajaxcall(_this.attr('href'), {}, function (data) {
            if(data.state == 1) {
                _this.before(data.html);
                var next_page = ($(data.page).find('a[rel="next"]').attr('href'));
                if(next_page) {
                    _this.attr('href', next_page);
                } else {
                    _this.remove();
                }
            }
        }, 'get', 'json');
        return false;
    });

    // 注册'infinite'事件处理函数
    $(document).on('infinite', '.infinite-scroll-bottom', function() {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        // 模拟1s的加载过程
        setTimeout(function() {
            // 重置加载flag
            loading = false;
            var pageUrl = getNextPage();
            if (pageUrl == undefined) {
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                $('.infinite-scroll-preloader').remove();
                $('#pagination').show().html('~到底了~');
                return;
            }
            // 获取列表内容
            getList(pageUrl);
            //容器发生改变,如果是js滚动，需要刷新滚动
            $.refreshScroller();
        }, 1000);
    });
    $(document).on('click', '.back', function () {
        window.history.back();
    });
});
